<?php
/**
 * Created by PhpStorm.
 * User: yangwang
 * Date: 2024-04-19
 * Time: 15:17
 */

namespace App\Kuafu\Export\Service\ExportFactory;


use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Shop\Service\ShopRecordService;
use App\Kuafu\Statistics\Service\StatisticsService;
use Illuminate\Support\Str;

class ExportShopRecordListService extends BaseExportService
{
    private $localPath = '';
    public function query(): self
    {
        $params       = $this->params['otherParams'] ?? [];

        $dimCode          = ($params['dimCode'] ?? '');
        $shopIds          = ($params['shopIds']??[]);
        $status           = ($params['status'] ?? null);
        $areaCode         = ($params['areaCode'] ?? 0);
        $inShopStaffCount = ($params['inShopStaffCount'] ?? null);
        $recordStatus     = ($params['recordStatus'] ?? null);
        $councilorId      = ($params['councilorId'] ?? 0);
        $activityDays     = ($params['activityDays'] ?? 0);
        $sortField        = ($params['sortField'] ?? '');
        $sortOrder        = ($params['sortOrder'] ?? '');

        ini_set('memory_limit', '2G');

        $dataArr = ShopRecordService::getList(
            0,0,$shopIds,$dimCode,$areaCode,$status,
            $inShopStaffCount,$recordStatus,$councilorId,[],true, $activityDays
        )['lists'];

        $this->localPath = sys_get_temp_dir() . '/' . Str::random();
        $this->streamExport($dataArr, $this->localPath);

        return $this;
    }

    public function path(): string
    {
        return $this->upload($this->localPath);
    }

    public function streamExport(
        array $list,
        string $path
    ): void {

        $fileName = $this->exportDownloadModel->name;

        StatisticsService::spreadsheetExcel([
            [
                'title' => ExportDownloadModel::FILE_TYPE_TEXT[ExportDownloadModel::FILE_TYPE_WEB_SHOP_RECORD_LIST],
                'info'  => [],
                'rows'  => self::buildRows($list),//
            ]
        ], $fileName, $path);
    }

    public static function buildRows(array $list)
    {
        $row[] = [
            '门店编号','门店名称','门店状态','所属区域','门店督导',
            '总在职员工数','需到店员工数','证件缺失/过期','通过审核人数',
            '驳回人数','待审核', '即将到期的员工数',
            '战区','省','市','区',
            '商家最近操作','审核最近操作'
        ];
        foreach ($list as $item){
            $row[] = [
                $item['shopCode'],$item['name'],$item['shopStatus'],$item['area'], $item['councilorName'],
                $item['staffCount'],$item['inShopStaffCount'],$item['cardAbnormalCount'],
                $item['approvedCount'],$item['rejectCount'],$item['pendingCount'], $item['expireCount'],
                $item['warZone'],$item['provinceName'], $item['cityName'],$item['districtName'],
                $item['lastManagerUpdateTime'],$item['lastAuditTime']
            ];
        }
        return $row;
    }

}
